package com.stylefeng.guns.modular.revenue.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.aop.Platform;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.revenue.model.Revenue;
import com.stylefeng.guns.modular.revenue.service.IRevenueService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 盈亏报表控制器
 *
 * @author fengshuonan
 * @Date 2018-06-30 09:24:50
 */
@Controller
@RequestMapping("/revenue")
public class RevenueController extends BaseController {

    private String PREFIX = "/revenue/revenue/";

    @Autowired
    private IRevenueService revenueService;

    /**
     * 跳转到盈亏报表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "revenue.html";
    }

    /**
     * 跳转到添加盈亏报表
     */
    @RequestMapping("/revenue_add")
    public String revenueAdd() {
        return PREFIX + "revenue_add.html";
    }

    /**
     * 跳转到修改盈亏报表
     */
    @RequestMapping("/revenue_update/{revenueId}")
    public String revenueUpdate(@PathVariable Integer revenueId, Model model) {
        Revenue revenue = revenueService.selectById(revenueId);
        model.addAttribute("item",revenue);
        LogObjectHolder.me().set(revenue);
        return PREFIX + "revenue_edit.html";
    }

    /**
     * 获取盈亏报表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {

        return revenueService.selectList(null);
    }

    /**
     * 新增盈亏报表
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @BussinessLog(value = "新增盈亏报表")
    public Object add(Revenue revenue) {
        //获取当前操作用户平台
        revenue.setPlatform(ShiroKit.getUser().getDeptcode());
        revenue.setCreattime(new Date());
        if(revenueService.getViewPfr(revenue.getPlatform(), revenue.getRevtime())!=null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,DateUtil.formatDate(revenue.getRevtime(),null)+"报表数据已存在");
        }

        if (revenue.getRevtime()==null) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "报表统计时间不能为空");
        }
        if (StringUtils.isBlank(revenue.getPlatform())){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表所在平台编号不能为空");
        }
        revenueService.insert(revenue);
        return SUCCESS_TIP;
    }

    /**
     * 批量新增盈亏报表
     */
    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(List<Revenue> revenues) {
        for (Revenue revenue : revenues){
            if (StringUtils.isBlank(revenue.getPlatform())){
                throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表所在平台编号不能为空");
            }
            if (StringUtils.isBlank(revenue.getRevtime().toString())){
                throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表日期不能为空，请检查报表日期");
            }
        }

        revenueService.insertBatch(revenues);
        return SUCCESS_TIP;
    }

    /**
     * 删除盈亏报表
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除盈亏报表")
    public Object delete(@RequestParam Integer revenueId) {
        revenueService.deleteById(revenueId);
        return SUCCESS_TIP;
    }

    /**
     * 修改盈亏报表
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改盈亏报表")
    public Object update(Revenue revenue) {
        if (StringUtils.isBlank(revenue.getPlatform())){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表日期不能为空");
        }
        revenue.setUpdatetime(new Date());
        revenue.setRevtime(null);
        revenue.setPlatform(null);
        revenueService.updateById(revenue);
        return SUCCESS_TIP;
    }

    /**
     * 盈亏报表详情
     */
    @RequestMapping(value = "/detail/{revenueId}")
    @ResponseBody
    public Object detail(@PathVariable("revenueId") Integer revenueId) {
        return revenueService.selectById(revenueId);
    }

    /**
     * 查询盈亏
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "select")
    @ResponseBody
    public Object select(@RequestParam(required = false) String beginDate,@RequestParam(required = false) String endDate,@Platform String platform) throws Exception {
        //分页查询
        Page<Revenue> page = new PageFactory<Revenue>().defaultPage();
        //组装查询
        EntityWrapper<Revenue> wrapper = new EntityWrapper<Revenue>();
        wrapper.eq("platform",platform);
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("revtime", beginDate);
        }else{
            wrapper.ge("revtime", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("revtime", endDate);
        }else{
            wrapper.le("revtime", DateUtil.today(1));
        }
        wrapper.orderBy("revtime",false);
        Page<Revenue> object =this.revenueService.selectPage(page,wrapper);
        //填充字典类型
        object.setRecords((List<Revenue>)new BaseModelWarpper(object.getRecords(),Revenue.class).warpToObj());
        return super.packForBT(object);
    }



  /**
   * 描述:合计
   * 创建人: xiang
   * 日期: 2018/8/8
   * 时间: 11:51
   */
    @RequestMapping(value = "tatol")
    @ResponseBody
    public Object tatol(@Platform String platform,@RequestParam(required = false) String beginDate,@RequestParam(required = false)  String endDate) throws Exception {
        //组装查询
        EntityWrapper<Revenue> wrapper = new EntityWrapper<Revenue>();
        wrapper.setSqlSelect("SUM(AG_profit) AS agProfit,SUM(BBin_profit) AS bbinProfit,SUM(PT_profit) AS ptProfit,SUM(MG_profit) AS mgProfit,SUM(DS_profit) AS dsProfit,SUM(VR_profit) AS vrProfit,SUM(KG_profit) AS kgProfit,SUM(SB_profit) AS sbProfit,SUM(GP_profit) AS gpProfit,\n" +
                "SUM(lotter_profit) AS lotterProfit,SUM(hdzs_profit) AS hdzsProfit,SUM(rebate_profit) AS rebateProfit");
        wrapper.eq("platform",platform);
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("revtime", beginDate);
        }else{
            wrapper.ge("revtime", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("revtime", endDate);
        }else{
            wrapper.le("revtime", DateUtil.today(1));
        }
        Revenue object =this.revenueService.selectOne(wrapper);
        if(object==null){
            object= new   Revenue();
        }

        return object;
    }


    @RequestMapping("load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response,@RequestParam(required = false) String beginDate,@RequestParam(required = false) String endDate) {
        Map<String, Object> map = new HashMap<String, Object>();
        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/revenue.xlsx");

        map.put("gh", ShiroKit.getUser().getDeptName());
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);
        String platform = ShiroKit.getUser().getDeptcode();
        List<Map<String,Object>> revenuesList = revenueService.getExcelList(platform,beginDate,endDate);
        List<Map<String,Object>> revenuesTotal = revenueService.getExcelListTotal(platform,beginDate,endDate);
        map.put("List", revenuesList);
        map.put("Total", revenuesTotal);
        modelMap.put(TemplateExcelConstants.FILE_NAME, ShiroKit.getUser().getDeptName()+"盈亏报表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }




}
